// 认证相关工具函数

/**
 * 获取存储在localStorage中的token
 * @returns {string | null} token字符串或null
 */
export const getToken = (): string | null => {
  return localStorage.getItem("token");
};

/**
 * 设置token到localStorage
 * @param {string} token - 要存储的token
 */
export const setToken = (token: string): void => {
  localStorage.setItem("token", token);
};

/**
 * 清除localStorage中的token
 */
export const removeToken = (): void => {
  localStorage.removeItem("token");
  localStorage.removeItem("isLoggedIn");
};

/**
 * 检查用户是否已登录（是否有有效token）
 * @returns {boolean} 是否已登录
 */
export const isAuthenticated = (): boolean => {
  const token = getToken();
  return !!token;
};

/**
 * 从JWT token中解析用户信息（如果token是JWT格式）
 * @param {string} token - JWT token
 * @returns {any} 解析出的用户信息
 */
export const parseTokenPayload = (token: string): any => {
  try {
    // JWT token格式：header.payload.signature
    const parts = token.split(".");
    if (parts.length !== 3) {
      throw new Error("Invalid JWT token format");
    }

    // 解码payload部分（base64）
    const payload = parts[1];
    const decoded = atob(payload.replace(/-/g, "+").replace(/_/g, "/"));
    return JSON.parse(decoded);
  } catch (error) {
    console.error("Failed to parse token payload:", error);
    return null;
  }
};

/**
 * 检查token是否过期
 * @param {string} token - JWT token
 * @returns {boolean} token是否过期
 */
export const isTokenExpired = (token: string): boolean => {
  return false;
};

/**
 * 获取当前用户信息（从token中解析）
 * @returns {any} 用户信息对象
 */
export const getCurrentUser = (): any => {
  const token = getToken();
  if (!token) {
    return null;
  }

  return parseTokenPayload(token);
};

/**
 * 格式化Authorization header
 * @param {string} token - token字符串
 * @returns {string} 格式化后的Authorization header值
 */
export const formatAuthHeader = (token: string): string => {
  return `Bearer ${token}`;
};

/**
 * 从请求头中提取token
 * @param {string} authHeader - Authorization header值
 * @returns {string | null} 提取出的token
 */
export const extractTokenFromHeader = (authHeader: string): string | null => {
  return authHeader;
};

/**
 * 从响应头中提取并保存token
 * @param {Record<string, any>} headers - 响应头对象
 * @returns {string | null} 提取出的token
 */
export const extractAndSaveTokenFromResponse = (
  headers: Record<string, any>
): string | null => {
  // 尝试从多个可能的header字段中获取token
  const tokenHeader =
    headers["authorization"] ||
    headers["Authorization"] ||
    headers["x-auth-token"] ||
    headers["X-Auth-Token"] ||
    headers["access-token"] ||
    headers["Access-Token"];

  if (tokenHeader) {
    const token = extractTokenFromHeader(tokenHeader);
    if (token) {
      setToken(token);
      return token;
    }
  }

  return null;
};

/**
 * 自动刷新token的工具函数
 * @param {Function} refreshTokenApi - 刷新token的API函数
 * @returns {Promise<boolean>} 是否刷新成功
 */
export const autoRefreshToken = async (
  refreshTokenApi: () => Promise<any>
): Promise<boolean> => {
  try {
    const currentToken = getToken();
    if (!currentToken) {
      return false;
    }

    // 检查token是否即将过期（提前5分钟刷新）
    const payload = parseTokenPayload(currentToken);
    if (!payload || !payload.exp) {
      return false;
    }

    const expirationTime = payload.exp * 1000;
    const currentTime = Date.now();
    const fiveMinutes = 5 * 60 * 1000;

    if (currentTime >= expirationTime - fiveMinutes) {
      console.log("Token即将过期，正在自动刷新...");
      const response = await refreshTokenApi();

      if (response.success && response.data.token) {
        setToken(response.data.token);
        console.log("Token刷新成功");
        return true;
      }
    }

    return false;
  } catch (error) {
    console.error("自动刷新token失败:", error);
    return false;
  }
};

/**
 * 登出清理函数
 */
export const logout = (): void => {
  removeToken();
  // 可以在这里添加其他清理逻辑，如清除用户数据缓存等
  window.location.href = "/login";
};
